import Vue from 'vue'
import { loginByTicket, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN,ALL_APPS_MENU } from '@/store/mutation-types'
import { welcome, encryption } from '@/utils/util'
import router from '../../router'
import store from '../index'
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {},
    apps: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    },
    SET_APPS: (state, apps) => {
      state.apps = apps
    }
  },

  actions: {
    // 登录
    Login ({ commit }, ticket) {
      return new Promise((resolve, reject) => {
        loginByTicket(ticket).then(response => {
          // 存储token 设置过期时间
          const result = response
          Vue.ls.set(ACCESS_TOKEN, result.tokenValue, result.tokenTimeout)
          commit('SET_TOKEN', result.tokenValue)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 获取用户信息
    GetInfo ({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(response => {
          const result = response.data
          const role = {
            permissions: result.permissions
          }
          commit('SET_ROLES', role)
          commit('SET_INFO', result.sysUser)
          commit('SET_NAME', { name: result.sysUser.username, welcome: welcome() })
          commit('SET_AVATAR', result.sysUser.avatar)
          commit('SET_APPS',result.apps)
          resolve(result)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    Logout ({ commit, state }) {
      return new Promise((resolve) => {
        logout().then(() => {
          commit('SET_ROLES', [])
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove('TENANT_ID')
          commit('SET_TOKEN', '')
          resolve()
        }).catch(() => {
          commit('SET_ROLES', [])
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove('TENANT_ID')
          commit('SET_TOKEN', '')
          resolve()
        })
      })
    },
    // 推出删除token
    DelToken ({ commit }) {
      return new Promise((resolve, reject) => {
        logout().then(res => {
          commit('SET_ROLES', [])
          Vue.ls.remove(ACCESS_TOKEN)
          commit('SET_TOKEN', '')
          Vue.ls.remove('TENANT_ID')
          resolve()
        })

      })
    },
  }
}

export default user
